package com.lkx.farmershop.controller;


import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.common.properties.JwtProperties;
import com.lkx.farmershop.jwt.NewJwtUtil;
import com.lkx.farmershop.model.dto.UserLoginDTO;
import com.lkx.farmershop.model.entity.User;
import com.lkx.farmershop.model.vo.UserLoginVO;
import com.lkx.farmershop.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lwc
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public ApiResult<UserLoginVO> wxlogin(@RequestBody UserLoginDTO userLoginDTO){
        // 用户微信登录
        User user = userService.wxlogin(userLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        Long userId = user.getId();
        claims.put("userId", userId);
        String token = NewJwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(userId)
                .openid(user.getOpenid())
                .token(token)
                .build();
        return ApiResult.success(userLoginVO);
    }

}
